/**
 * 获取添加角色激活码接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

//getAddServiceCode
let index = function(getData, postData, config, redis, db) {
	let deferred = Q.defer();
	if(postData.serviceName && postData.serviceAuth) {
		let registerCode = '';
		db.select('allowServices', {name: postData.serviceName}).then(function(allowService) {
			if(allowService.length > 0) {
				//已存在同样的角色名，不可重复添加
				deferred.reject('-0167');
				return deferred.promise;
			}
			else {
				return util.createRandomStr(6);
			}
		}, function() {
			//获取角色列表失败
			deferred.reject('-0166');
		}).then(function(_registerCode) {
			registerCode = _registerCode;
			return redis.set('registerCode-' + registerCode, JSON.stringify({
				 storeId: postData.storeId,
				 serviceName: postData.serviceName,
				 serviceAuth: postData.serviceAuth
			}));
		}, function() {
			//生成六位激活码失败
			deferred.reject('-0168');
		}).then(function() {
			return redis.expire('registerCode-' + registerCode, 1800);
		}, function() {
			//存放激活码到redis失败
			deferred.reject('-0169');
		}).then(function() {
			deferred.resolve({
				registerCode: registerCode
			});
		}, function() {
			//设置激活码生命周期失败
			deferred.reject('0170');
		});
	}
	else {
		deferred.reject();
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
}